package leetcode.code0227;

import java.util.Stack;

import leetcode.IDebug;
import leetcode.helper.HelpDebug;

//执行用时：10 ms, 在所有 Java 提交中击败了81.86%的用户
//
//内存消耗：40.6 MB, 在所有 Java 提交中击败了43.47%的用户
//
//通过测试用例：109 / 109
public class Solution implements IDebug {

	public int calculate(String s) {
		int len = s.length();
		char[] cs = s.toCharArray();
		Stack<Integer> nums = new Stack<>();
		Stack<Character> ops = new Stack<>();
		ops.add('+');
		int num = 0;
		char op = 0, c = 0;
		for (int i = 0; i < len; i++) {
			if ((c = cs[i]) >= '0' && c <= '9') {
				num = num * 10 + c - '0';
			} else if (c == '+' || c == '-' || c == '*' || c == '/') {
				this.cal(op, ops, nums, num);
				ops.add(c);
				num = 0;
			}
		}
		this.cal(op, ops, nums, num);
		int ans = 0;
		while (!ops.isEmpty()) {
			if (ops.pop() == '+') {
				ans += nums.pop();
			} else {
				ans -= nums.pop();
			}
		}
		return ans;
	}

	private void cal(char op, Stack<Character> ops, Stack<Integer> nums, int num) {
		if ((op = ops.peek()) == '*') {
			nums.add(nums.pop() * num);
			ops.pop();
		} else if (op == '/') {
			nums.add(nums.pop() / num);
			ops.pop();
		} else {
			nums.add(num);
		}
	}

	public void debug5() {
		HelpDebug.compare(4067, this.calculate("282-1*2*13-30-2*2*2/2-95/5*2+55+804+3024"));

	}

	@Override
	public void debug1() {
		HelpDebug.compare(7, this.calculate("3+2*2"));

	}

	@Override
	public void debug2() {
		HelpDebug.compare(1, this.calculate(" 3/2 "));

	}

	@Override
	public void debug3() {
		HelpDebug.compare(5, this.calculate(" 3+5 / 2 "));
	}

	@Override
	public void debug4() {
		HelpDebug.compare(-1, this.calculate(" 3+2*2-12+33/ 7"));

	}

	public static void main(String[] args) {
		Solution so = new Solution();
		so.debug5();
		so.debug4();
		so.debug1();
		so.debug2();
		so.debug3();

	}

}
